package com.ssy.wireless.task;

import com.ssy.wireless.entity.ApDeviceOnlineStat;
import com.ssy.wireless.entity.Hotspot;
import com.ssy.wireless.mapper.ApDeviceMapper;
import com.ssy.wireless.mapper.ApDeviceOnlineStatMapper;
import com.ssy.wireless.mapper.HotspotMapper;
import com.ssy.wireless.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by cofey on 16/11/22.
 */
@Component
@Slf4j
public class ApDeviceOnlineStatTask {

    @Autowired
    private HotspotMapper hotspotMapper;

    @Autowired
    private ApDeviceMapper apDeviceMapper;

    @Autowired
    private ApDeviceOnlineStatMapper apDeviceOnlineStatMapper;

    //每天整点执行一次
    @Scheduled(cron = "0 0 0/1 * * ?")
    @Transactional
    public void exec() {
        Date date = DateUtils.getTime();
        log.info("设备在线统计任务,{}开始执行...", DateUtils.formatYMDHMS(date));
        List<Hotspot> hotspots = hotspotMapper.select(null);
        for (Hotspot hotspot : hotspots) {
            int onlineCount = apDeviceMapper.selectOnlineCount(hotspot.getEntId(), hotspot.getType(), hotspot.getId());
            if (onlineCount > 0) {
                DateUtils.YearMonthWeekDayHour yearMonthWeekDay = DateUtils.getYearMonthWeekDay(date);
                ApDeviceOnlineStat stat = new ApDeviceOnlineStat();
                stat.setHourVal(yearMonthWeekDay.getHour());
                stat.setDayVal(yearMonthWeekDay.getDay());
                stat.setWeekVal(yearMonthWeekDay.getWeek());
                stat.setMonthVal(yearMonthWeekDay.getMonth());
                stat.setYearVal(yearMonthWeekDay.getYear());
                stat.setCreateTime(date);
                stat.setOnlineCount(onlineCount);
                stat.setHotspotType(hotspot.getType());
                stat.setEntId(hotspot.getEntId());
                stat.setHotspotId(hotspot.getId());
                apDeviceOnlineStatMapper.insert(stat);
            }else{
                log.info("{}没有在线设备数,无需统计", hotspot.getName());
            }
        }
        log.info("设备在线统计任务执行成功");
    }
}
